package com.stanyung.realtimeclient;

import com.stanyung.realtimeclient.common.ByteUtil;
import com.stanyung.realtimeclient.common.Constants;

public class Packet {

	private int cmd;
	private int seq;
	private byte zip;
	private byte protocolType;
	private Object data;
	
	private boolean heartBeat = false;

	public Packet() {
		super();
	}

	public Packet(int cmd, int seq, byte zip, byte protocolType, Object data) {
		super();
		this.cmd = cmd;
		this.seq = seq;
		this.zip = zip;
		this.protocolType = protocolType;
		this.data = data;
	}
	
	public static Packet newHeartBeatPacket() {
		Packet packet = new Packet();
		packet.setHeartBeat(true);
		return packet;
	}

	public static Packet parse(byte[] bytes) {
		int cmd = ByteUtil.bytes2Int(bytes, 0);
		int seq = ByteUtil.bytes2Int(bytes, 4);
		byte zip = bytes[8];
		byte protocolType = bytes[9];
		String d = new String(bytes, 10, bytes.length - 10);
		Packet packet = new Packet(cmd, seq, zip, protocolType, d);
		return packet;
	}

	public byte[] toBytes() {
		if(heartBeat) {
			return new byte[0];
		}
		String content = (String) data;
		byte[] dataBytes = content.getBytes();
		int dataLength = dataBytes.length;
		int len = Constants.HEAD_LENGTH + dataLength;
		byte[] buff = new byte[len];
		ByteUtil.putInt(buff, cmd, 0);
		ByteUtil.putInt(buff, seq, 4);
		buff[8] = zip;
		buff[9] = protocolType;
		System.arraycopy(dataBytes, 0, buff, 10, dataLength);
		return buff;
	}

	@Override
	public String toString() {
		return String.format("cmd = %d, seq = %d, zip = %d, protocolType = %d, data = %s", cmd, seq, zip, protocolType, data);
	}

	public int getCmd() {
		return cmd;
	}

	public void setCmd(int cmd) {
		this.cmd = cmd;
	}

	public int getSeq() {
		return seq;
	}

	public void setSeq(int seq) {
		this.seq = seq;
	}

	public byte getZip() {
		return zip;
	}

	public void setZip(byte zip) {
		this.zip = zip;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public byte getProtocolType() {
		return protocolType;
	}

	public void setProtocolType(byte protocolType) {
		this.protocolType = protocolType;
	}

	public boolean isHeartBeat() {
		return heartBeat;
	}

	public void setHeartBeat(boolean heartBeat) {
		this.heartBeat = heartBeat;
	}

}